<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Scripts extends CI_Controller {
    public function index(){
        echo "It works.";
    }
    
    public function overrideOrder() {
        $user_id = $this->input->post("uid");
        $meal_id = $this->input->post("meal_id");
        $comment = $this->input->post("comment");
        
        $this->load->model("user_orders");
        
        if ($this->user_orders->order($user_id, $meal_id, $comment)) {
            echo "good";
        }
        else {
            echo "Internal server database error when ordering";
        }
    }
    
    public function order(){
        $user_id = $this->input->post("uid");
        $meal_id = $this->input->post("meal_id");
        $comment = $this->input->post("comment");
        
        if ($user_id == null || $meal_id == null || $comment == null){
            echo "Invalid POST data";
            return;
        }
        $user_id = intval($user_id);
        $meal_id = intval($meal_id);
        
        //Load all the things
        $this->load->model("user_orders");
        $this->load->model("mealtimes");
        
        //Get's tonights meals
        $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"),date("m"),date("j")); 
        
        $orderable = $tonightsMeals->row()->mealtime_orderable;
        $cutoff = date("H:i:s", strtotime($tonightsMeals->row()->mealtime_cutoff));        
        $currentTime = date("H:i:s", time());
        
        if ($orderable == 1 && $currentTime < $cutoff) {
            //Allow the user to continue   

            $allergies = $this->checkForAllergies($user_id, $meal_id);
            
            if (empty($allergies)) {
                if ($this->user_orders->order($user_id,$meal_id, $comment)){
                    //Success
                    echo "good";
                }
                else{
                    //Failure
                    echo "There was an error server side.";
                }
            }
            else {
                //Tell the user that they have allergies
                // Load XML writer library
                $this->load->library('Xml_writer');
                // Initiate class
                $xml = new Xml_writer;
                $xml->setRootName('data');
                $xml->initiate();
                
                foreach ($allergies as $id => $name) {
                    $xml->startBranch('allergy');
                    $xml->addNode('name', $name);
                    $xml->addNode('id', $id);
                    $xml->endBranch();
                }
                
                // Print the XML to screen
                $xml->getXml(true);
            }
        }
        else {
            //Send notification to user stating that they're past the cutoff period
            echo "Past the cut-off time for meal voting.";
        }
    }
    
    public function overrideVote() {
        //This funciton will be called by the device if they still wish to vote
        //on a meal even though they have triggered allergies.
        
        $user_id = $this->input->post("uid");
        $mtm_id = $this->input->post("meal_id");
        
        if ($user_id == null || $mtm_id == null){
            echo "Invalid POST data";
            return;
        }
        
        $this->load->model("mealtimes");
        $this->load->model("user_votes");
        
        $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"),date("m"),date("j")); 
        
        if ($this->user_votes->vote($user_id, $tonightsMeals, $mtm_id)) {
            echo "good";
        }
        else {
            echo "Internal server database error when voting";
        }
    }
    
    public function vote(){
        $user_id = $this->input->post("uid");
        $mtm_id = $this->input->post("meal_id");
        
        if ($user_id == null || $mtm_id == null){
            echo "Invalid POST data";
            return;
        }
        
        //Load all the things!
        $this->load->model("mealtimes");
        $this->load->model("user_votes");
        date_default_timezone_set('Australia/Sydney');
        
        //Get's tonights meals
        $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"),date("m"),date("j")); 
        
        $cutoff = date("H:i:s", strtotime($tonightsMeals->row()->mealtime_cutoff));        
        $currentTime = date("H:i:s", time());
        
        if ($currentTime < $cutoff) {
            //Allow the user to continue            
            $allergies = $this->checkForAllergies($user_id, $mtm_id);
            
            if (empty($allergies)) {
                //Check user voted
                if ($this->user_votes->vote($user_id, $tonightsMeals, $mtm_id)) {
                    echo "good";
                }
                else {
                    echo "Internal server database error when voting";
                }
            }
            else {
                //Tell the user that they have allergies
                // Load XML writer library
                $this->load->library('Xml_writer');
                // Initiate class
                $xml = new Xml_writer;
                $xml->setRootName('data');
                $xml->initiate();
                
                foreach ($allergies as $id => $name) {
                    $xml->startBranch('allergy');
                    $xml->addNode('name', $name);
                    $xml->addNode('id', $id);
                    $xml->endBranch();
                }
                
                // Print the XML to screen
                $xml->getXml(true);
            }
        }
        else {
            //Send notification to user stating that they're past the cutoff period
            echo "Past the cut-off time for meal voting.";
        }
    }
    
    public function futureMeals(){
        $this->load->model('mealtimes');
        $this->load->model('defaults');
        $this->load->library('Xml_writer');
        
        $xml = new Xml_writer;
        $xml->setRootName('data');
        $xml->initiate();
        
        
        for($i = 1; $i <= $this->defaults->getFutureCount(); $i++){
            $currentDay = strtotime("+$i day");
            
            $xml->startBranch('day');
            $xml->addNode('date',date('D (jS M, Y)',$currentDay));
            
            $year = date('Y',$currentDay);
            $month = date('n',$currentDay);
            $day = date('j',$currentDay);
            
            $meals = $this->mealtimes->getMealsYMD($year,$month,$day);
            
            foreach ($meals->result() as $result){
                $xml->startBranch('meal');
                
                $xml->addNode('id',$result->mealtime_meals_id);
                $xml->addNode('name',$result->meal_title);
                $xml->addNode('description', $result->meal_description);
                
                $xml->endBranch();
            }
            
            $xml->endBranch();
        }
        
        $xml->getXml(true);
    }
    
    /*
     * Function returns true if there are no allergies
     */    
    private function checkForAllergies($user_id, $mealtime_meals_id) {
        //Select the allergies for the current user
        
        $this->load->model('mealtime_meals');
        $this->load->model('meals');
        
        $meal_id = $this->mealtime_meals->getMealID($mealtime_meals_id);
        
        if ($meal_id < 0){
            return null;
        }
        
        $mealBasetypes = $this->meals->getBasetypes($meal_id);
        
        $mbArray = array();
        foreach($mealBasetypes->result() as $result){
            $mbArray[] = $result->basetype_id;
        }
        
        
        $this->load->model('users');
        $userBasetypes = $this->users->getBasetypes($user_id);
        
        $ubArray = array();
        if ($userBasetypes != null){
            foreach($userBasetypes->result() as $result){
                if (in_array($result->basetype_id, $mbArray)){
                    $ubArray[$result->basetype_id] = $result->basetype_title;
                }
            }
        }
        
        return $ubArray;
    }
    
    public function getAllergies(){
        
        $user_id = $this->input->post("user_id");
        
        $this->load->library('Xml_writer');
        $this->load->model('users');
        $this->load->model('basetypes');
        
        $allergies = $this->users->getBasetypes($user_id);
        $aArray = array();
        
        if ($allergies != null){
            foreach($allergies->result() as $result){
                $aArray[] = $result->basetype_id;
            }
        }
        
        $basetypes = $this->basetypes->getAll();
        
        $xml = new Xml_writer;
        $xml->setRootName('data');
        $xml->initiate();
                
        foreach($basetypes->result() as $result){
            $xml->startBranch('allergy');
            
            $xml->addNode('id', $result->basetype_id);
            $xml->addNode('name', $result->basetype_title);
            
            if (in_array($result->basetype_id, $aArray)){
                $xml->addNode('selected', 1);
            }
            else{
                 $xml->addNode('selected', 0);
            }
            
            $xml->endBranch();
        }
        
        $xml->getXml(true);
    }
    
    public function saveAllergies(){
        
        $this->load->model('users');
        
        $allergies = $this->input->post('allergies');
        $user_id = $this->input->post('user_id');
        
        if ($this->users->updateBasetypes($user_id,$allergies)){
            echo "good";
        }       
        else{
            echo "Internal server error when updating meals";
        }
        
    }
    
}